import { ref, reactive, readonly } from 'vue'
import { createVodService } from '../utils/huawei-vod'
import type {
  PlayInfo,
  ChunkedUploadParams,
  DirectUploadParams,
  UploadProgress
} from '../types/vod'

/**
 * VOD播放器组合式函数
 */
export function useVodPlayer(config?: {
  projectId?: string
  region?: string
}) {
  const vodService = createVodService(config)

  // 响应式状态
  const loading = ref(false)
  const error = ref('')
  const playInfo = ref<PlayInfo | null>(null)


  // 分段上传状态
  const uploadStatus = reactive({
    isUploading: false,
    progress: 0,
    currentChunk: 0,
    totalChunks: 0,
    stage: '' as UploadProgress['stage'],
    message: ''
  })


  /**
   * 直接获取已存在媒资的播放信息
   */
  const getPlayInfo = async (assetId: string): Promise<PlayInfo> => {
    try {
      loading.value = true
      error.value = ''

      const info = await vodService.getPlayInfo(assetId)
      playInfo.value = info

      return info
    } catch (err) {
      const errorMessage = err instanceof Error ? err.message : '获取播放信息失败'
      error.value = errorMessage
      throw err
    } finally {
      loading.value = false
    }
  }

  /**
   * 获取最佳播放URL（选择最高清晰度）
   */
  const getBestPlayUrl = (info?: PlayInfo): string => {
    const currentInfo = info || playInfo.value
    if (!currentInfo?.playUrls.length) return ''

    // 按清晰度排序，选择最高清晰度
    const sortedUrls = [...currentInfo.playUrls].sort((a, b) => {
      const qualityOrder = { '4K': 4, '2K': 3, '1080P': 2, '720P': 1, '480P': 0 }
      return (qualityOrder[b.quality as keyof typeof qualityOrder] || 0) -
        (qualityOrder[a.quality as keyof typeof qualityOrder] || 0)
    })

    return sortedUrls[0]?.url || ''
  }

  /**
   * 根据清晰度获取播放URL
   */
  const getPlayUrlByQuality = (quality: string, info?: PlayInfo): string => {
    const currentInfo = info || playInfo.value
    if (!currentInfo?.playUrls.length) return ''

    const url = currentInfo.playUrls.find(item => item.quality === quality)
    return url?.url || getBestPlayUrl(currentInfo)
  }

  /**
   * 分段上传视频文件
   */
  const uploadByChunks = async (params: ChunkedUploadParams): Promise<string> => {
    try {
      loading.value = true
      error.value = ''
      uploadStatus.isUploading = true
      uploadStatus.progress = 0
      uploadStatus.currentChunk = 0
      uploadStatus.totalChunks = 0
      uploadStatus.stage = 'creating_asset'
      uploadStatus.message = '准备上传...'

      // 设置进度回调
      const paramsWithProgress: ChunkedUploadParams = {
        ...params,
        onProgress: (progress: UploadProgress) => {
          uploadStatus.progress = progress.percentage
          uploadStatus.currentChunk = progress.currentChunk
          uploadStatus.totalChunks = progress.totalChunks
          uploadStatus.stage = progress.stage

          const stageMessages = {
            'creating_asset': '创建媒资...',
            'initializing': '初始化上传任务...',
            'uploading': `上传分段 ${progress.currentChunk}/${progress.totalChunks}...`,
            'merging': '合并分段...',
            'confirming': '确认上传...',
            'completed': '上传完成'
          }
          uploadStatus.message = stageMessages[progress.stage as keyof typeof stageMessages] || '处理中...'

          // 调用原始进度回调
          params.onProgress?.(progress)
        }
      }

      const assetId = await vodService.uploadAssetByChunks(paramsWithProgress)
      uploadStatus.isUploading = false
      uploadStatus.message = '上传成功'

      return assetId
    } catch (err) {
      const errorMessage = err instanceof Error ? err.message : '分段上传失败'
      error.value = errorMessage
      uploadStatus.isUploading = false
      uploadStatus.message = errorMessage
      throw err
    } finally {
      loading.value = false
    }
  }

  /**
   * 分段上传并获取播放地址
   */
  const uploadAndGetPlayInfo = async (params: ChunkedUploadParams): Promise<PlayInfo> => {
    try {
      loading.value = true
      error.value = ''

      const info = await vodService.uploadAssetAndGetPlayInfo(params)
      playInfo.value = info

      return info
    } catch (err) {
      const errorMessage = err instanceof Error ? err.message : '上传并获取播放信息失败'
      error.value = errorMessage
      throw err
    } finally {
      loading.value = false
    }
  }

  /**
   * 直接上传（20MB以下文件）
   */
  const uploadDirect = async (params: DirectUploadParams): Promise<{
    assetId: string
    status: string
    playInfo?: any
  }> => {
    try {
      loading.value = true
      error.value = ''

      const result = await vodService.uploadAssetDirect(params)

      return result
    } catch (err) {
      const errorMessage = err instanceof Error ? err.message : '直接上传失败'
      error.value = errorMessage
      throw err
    } finally {
      loading.value = false
    }
  }

  /**
   * 重置状态
   */
  const reset = () => {
    loading.value = false
    error.value = ''
    playInfo.value = null
    uploadStatus.isUploading = false
    uploadStatus.progress = 0
    uploadStatus.currentChunk = 0
    uploadStatus.totalChunks = 0
    uploadStatus.stage = 'creating_asset'
    uploadStatus.message = ''
  }

  return {
    // 状态
    loading: readonly(loading),
    error: readonly(error),
    playInfo: readonly(playInfo),
    uploadStatus: readonly(uploadStatus),

    // 方法
    getPlayInfo,
    getBestPlayUrl,
    getPlayUrlByQuality,
    uploadByChunks,
    uploadAndGetPlayInfo,
    uploadDirect,
    reset,

    // VOD服务实例（高级用法）
    vodService
  }
}
